package com.bobi.tfca.ui.mainnavigation.user.member

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.navigation.findNavController
import androidx.viewpager2.widget.ViewPager2
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentMemberManageBinding
import com.bobi.tfca.ui.adapter.MemManagePagerAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class MemberManageFragment : BaseFragment<FragmentMemberManageBinding, ViewModel>(
    FragmentMemberManageBinding::inflate,
    null,
    true
) {
    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: TabLayout
    private lateinit var pagerAdapter: MemManagePagerAdapter

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentMemberManageBinding,
        viewModel: ViewModel?,
        savedInstanceState: Bundle?
    ) {
        // 设置topPanel
        setTopPanelStyle(binding)

        // 初始化ViewPager
        viewPager = binding.vpMember
        pagerAdapter = MemManagePagerAdapter(this).apply {
            add { MemberStillFragment() }
            add { MemberLeaveFragment() }
        }
        viewPager.adapter = pagerAdapter

        // 初始化tablelayout
        tabLayout = binding.tabLayout
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            when(position) {
                0 -> tab.text = "在会"
                1 -> tab.text = "退会"
            }
        }.attach()
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentMemberManageBinding) {
        val topPanel = binding.topPanel
        topPanel.leftImage.setOnClickListener {
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        topPanel.titleText.text = "会员管理"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        viewPager.adapter = null
    }

    override fun resumeFragment(viewModel: ViewModel?) {
        super.resumeFragment(viewModel)
        if (viewPager.adapter == null) {
            pagerAdapter = MemManagePagerAdapter(this).apply {
                add { MemberStillFragment() }
                add { MemberLeaveFragment() }
            }
            viewPager.adapter = pagerAdapter
        }
    }
}